import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getStorage, setStorage } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const ORIGINAL_THEME = '#1890ff' // default color

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  const PICKER_THEME = getStorage('PICKER_THEME_INIT') || 'false'
  if (PICKER_THEME === 'false') {
    const theme = store.state.settings.theme
    if (ORIGINAL_THEME !== theme) {
      const themeCluster = [theme.replace('#', '')]
      for (let i = 0; i <= 9; i++) {
        themeCluster.push(tintColor(theme.replace('#', ''), Number((i / 10).toFixed(2))))
      }
      themeCluster.push(shadeColor(theme.replace('#', ''), 0.1))
      const originalCluster = [ORIGINAL_THEME.replace('#', '')]
      for (let i = 0; i <= 9; i++) {
        originalCluster.push(tintColor(ORIGINAL_THEME.replace('#', ''), Number((i / 10).toFixed(2))))
      }
      originalCluster.push(shadeColor(ORIGINAL_THEME.replace('#', ''), 0.1))
      const styles = [].slice.call(document.querySelectorAll('style'))
        .filter(style => {
          const text = style.innerText
          return new RegExp(ORIGINAL_THEME, 'i').test(text) && !/Chalk Variables/.test(text)
        })
      styles.forEach(style => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        let newStyle = innerText
        originalCluster.forEach((color, index) => {
          newStyle = newStyle.replace(new RegExp(color, 'ig'), themeCluster[index])
        })
        style.innerText = newStyle
      })
    }

    setStorage('PICKER_THEME_INIT', true)
  }

  // set page title
  document.title = getPageTitle(to.meta.title)

  next()
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})

const tintColor = (color, tint) => {
  let red = parseInt(color.slice(0, 2), 16)
  let green = parseInt(color.slice(2, 4), 16)
  let blue = parseInt(color.slice(4, 6), 16)

  if (tint === 0) { // when primary color is in its rgb space
    return [red, green, blue].join(',')
  } else {
    red += Math.round(tint * (255 - red))
    green += Math.round(tint * (255 - green))
    blue += Math.round(tint * (255 - blue))

    red = red.toString(16)
    green = green.toString(16)
    blue = blue.toString(16)

    return `#${red}${green}${blue}`
  }
}

const shadeColor = (color, shade) => {
  let red = parseInt(color.slice(0, 2), 16)
  let green = parseInt(color.slice(2, 4), 16)
  let blue = parseInt(color.slice(4, 6), 16)

  red = Math.round((1 - shade) * red)
  green = Math.round((1 - shade) * green)
  blue = Math.round((1 - shade) * blue)

  red = red.toString(16)
  green = green.toString(16)
  blue = blue.toString(16)

  return `#${red}${green}${blue}`
}
